package com.audaque.springboot.foshanupload.gateway.factory;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author zgb
 * @desc ...
 * @date 2023-08-01 16:32:58
 */
@Component
public class MyParamRoutePredicateFactory extends AbstractRoutePredicateFactory<MyParamRoutePredicateFactory.Config> {


    public MyParamRoutePredicateFactory() {
        //当前类的Config类，会利用反射创建Config并赋值，在apply传回来
        super(MyParamRoutePredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        //"tokenValue"跟Config的接收字段一致
        return Arrays.asList("param");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        //这里获取的config对象就是下面自定义的Config对象
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                ServerHttpRequest request = exchange.getRequest();
                if (request.getQueryParams().containsKey(config.param)) {
                    request.getQueryParams().get(config.param)  //get方法获取的是一个List，而且List中只有一个值
                            .forEach(value ->
                                    System.out.printf("----------断言-----%s = %s-----", config.param, value));
                }
                return true;
            }
        };
    }
    //用来接收配置文件定义的值
    public static class Config {

        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}
